import React, { Component, Dispatch } from 'react';
import { connect } from 'dva';
import { withRouter, Route, RouteComponentProps } from 'dva/router';
import { Result } from 'antd';

interface AuthorizedRouteProps extends RouteComponentProps<any> {
  component?: React.ComponentType<RouteComponentProps<any>> | React.ComponentType<any>;
  path?: string | string[];
  dispatch: Dispatch<any>;
}

class AuthorizedRoute extends Component<AuthorizedRouteProps> {

  state = {
    isException: false,
    isAuthorized: false,
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/init',
      callback: response => {
        if (response) {
          this.setState({
            isAuthorized: true
          });
        } else {
          this.setState({
            isException: true,
          });
        }
        const loader = document.querySelector('#loader-wrapper');
        if (loader) {
          document.body.removeChild(loader);
        }
      }
    });
  }

  render(): any {
    const { component, ...rest } = this.props;
    const { isAuthorized, isException } = this.state;
    return isAuthorized ? (
      <Route {...rest} component={component} />
    ) : isException ? (
      <Result
        status="500"
        title="500"
        subTitle="服务器出现错误，请联系管理员"
      />
    ) : null;
  }
}
export default connect()(withRouter(AuthorizedRoute));
